<template>
  <div class="container">
    <a-card class="general-card">
      <template #title>货物信息管理</template>
      <template #extra>
        <a-space>
          <a-button type="primary" @click="openAddModal">
            <template #icon><icon-plus /></template>
            新增货物
          </a-button>
          <a-button status="danger" @click="handleBatchDelete" :disabled="selectedRowKeys.length === 0">
            <template #icon><icon-delete /></template>
            批量删除
          </a-button>
          <a-button @click="handleImport">
            <template #icon><icon-import /></template>
            批量导入
          </a-button>
          <a-button @click="handleExport">
            <template #icon><icon-export /></template>
            导出数据
          </a-button>
        </a-space>
      </template>
      
      <!-- 搜索区域 -->
      <a-form :model="searchForm" class="search-form" layout="inline">
        <a-form-item field="code" label="货物编码">
          <a-input v-model="searchForm.code" placeholder="请输入货物编码" allow-clear />
        </a-form-item>
        <a-form-item field="name" label="货物名称">
          <a-input v-model="searchForm.name" placeholder="请输入货物名称" allow-clear />
        </a-form-item>
        <a-form-item field="category" label="货物分类">
          <a-select v-model="searchForm.category" placeholder="请选择货物分类" allow-clear :popup-max-height="300" :trigger-props="{ autoFitPopupWidth: true }">
            <a-option v-for="item in categoryOptions" :key="item.value" :value="item.value">{{ item.label }}</a-option>
            <template #empty>
              <div style="text-align: center; color: #999; padding: 10px 0">
                暂无分类数据
              </div>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item field="status" label="货物状态">
          <a-select v-model="searchForm.status" placeholder="请选择货物状态" allow-clear>
            <a-option v-for="item in statusOptions" :key="item.value" :value="item.value">{{ item.label }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="fetchCargoList">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="() => {
              searchForm = {
                code: '',
                name: '',
                category: undefined,
                status: undefined
              };
              fetchCargoList();
            }">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-table
        :data="tableData"
        :loading="loading"
        :pagination="{
          total: pagination.total,
          current: pagination.current,
          pageSize: pagination.pageSize,
          showTotal: true,
          showJumper: true,
          showPageSize: true,
          pageSizeOptions: [10, 20, 50, 100]
        }"
        :bordered="false"
        stripe
        :row-selection="{
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false
        }"
        v-model:selected-keys="selectedRowKeys"
        row-key="id"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #columns>
          <a-table-column title="货物编码" data-index="code" />
          <a-table-column title="货物名称" data-index="name" />
          <a-table-column title="分类" data-index="category.name" />
          <a-table-column title="规格" data-index="spec" />
          <a-table-column title="单位" data-index="unit">
            <template #cell="{ record }">
              {{ getUnitName(record.unit) }}
            </template>
          </a-table-column>
          <a-table-column title="供应商" data-index="supplier.name">
            <template #cell="{ record }">
              {{ record.supplier?.name || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="价格(元)" data-index="price">
            <template #cell="{ record }">
              ¥{{ record.price.toFixed(2) }}
            </template>
          </a-table-column>
          <a-table-column title="存储类型" data-index="storage_type">
            <template #cell="{ record }">
              {{ getStorageTypeText(record.storage_type) }}
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="180">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="handleEdit(record)">
                  <template #icon><icon-edit /></template>
                  编辑
                </a-button>
                <a-popconfirm
                  :content="`确认${record.status === 1 ? '禁用' : '启用'}货物'${record.name}'吗？`"
                  @ok="handleToggleStatus(record)"
                  position="br"
                >
                  <a-button type="text" size="small" :status="record.status === 1 ? 'danger' : 'success'">
                    {{ record.status === 1 ? '禁用' : '启用' }}
                  </a-button>
                </a-popconfirm>
                <a-popconfirm
                  content="确定要删除这个货物吗？此操作不可恢复。"
                  @ok="handleDelete(record)"
                  position="br"
                  type="warning"
                >
                  <a-button type="text" status="danger" size="small">
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑货物弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="isEdit ? '编辑货物' : '新增货物'"
      @ok="handleSubmit"
      @cancel="closeModal"
      :footer="false"
      :width="700"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="code" label="货物编码" required>
              <a-input-group>
                <a-input
                  v-model="formData.code"
                  placeholder="请输入货物编码"
                  :disabled="isEdit"
                  style="width: calc(100% - 104px)"
                />
                <a-button @click="generateCargoCode" :disabled="isEdit">自动生成</a-button>
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="name" label="货物名称" required>
              <a-input
                v-model="formData.name"
                placeholder="请输入货物名称"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="category_id" label="货物分类" required>
              <a-select
                v-model="formData.category_id"
                placeholder="请选择货物分类"
                :popup-max-height="300"
                :trigger-props="{ autoFitPopupWidth: true }"
              >
                <a-option
                  v-for="item in categoryOptions"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="unit" label="单位" required>
              <a-select
                v-model="formData.unit"
                placeholder="请选择单位"
              >
                <a-option v-for="item in unitOptions" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="spec" label="规格" required>
              <a-input
                v-model="formData.spec"
                placeholder="请输入规格，如500g/袋"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="price" label="货物价格">
              <a-input-number
                v-model="formData.price"
                placeholder="请输入价格"
                :precision="2"
                :min="0"
                mode="button"
                style="width: 100%"
              >
                <template #prefix>¥</template>
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item field="initialStock" label="初始库存">
              <a-input-number
                v-model="formData.initialStock"
                placeholder="请输入库存数量"
                :min="0"
                mode="button"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="minStock" label="库存下限">
              <a-input-number
                v-model="formData.minStock"
                placeholder="请输入库存下限"
                :min="0"
                mode="button"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="maxStock" label="库存上限">
              <a-input-number
                v-model="formData.maxStock"
                placeholder="请输入库存上限"
                :min="0"
                mode="button"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="productionDate" label="生产日期">
              <a-date-picker
                v-model="formData.productionDate"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="expirationDate" label="有效期至">
              <a-date-picker
                v-model="formData.expirationDate"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="supplier_id" label="供应商">
              <a-select
                v-model="formData.supplier_id"
                placeholder="请选择供应商"
                :popup-max-height="300"
                :trigger-props="{ autoFitPopupWidth: true }"
                allow-clear
              >
                <a-option
                  v-for="item in supplierOptions"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-option>
                <template #empty>
                  <div style="text-align: center; color: #999; padding: 10px 0">
                    暂无供应商数据
                  </div>
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="storage_type" label="存储类型" required>
              <a-select
                v-model="formData.storage_type"
                placeholder="请选择存储类型"
              >
                <a-option v-for="item in storageTypeOptions" :key="item.value" :value="item.value">
                  {{ item.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item field="status" label="货物状态" required>
          <a-radio-group v-model="formData.status" type="button">
            <a-radio :value="1">正常</a-radio>
            <a-radio :value="2">缺货</a-radio>
            <a-radio :value="3">即将停产</a-radio>
            <a-radio :value="4">新品</a-radio>
            <a-radio :value="5">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item field="description" label="货物描述">
          <a-textarea
            v-model="formData.description"
            placeholder="请输入货物描述"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
        
        <div class="modal-footer">
          <a-space>
            <a-button @click="closeModal">取消</a-button>
            <a-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>

    <!-- 批量导入货物弹窗 -->
    <a-modal
      v-model:visible="importVisible"
      title="批量导入货物"
      @ok="handleImportSubmit"
      @cancel="importVisible = false"
    >
      <a-upload
        :custom-request="customRequest"
        :show-file-list="false"
        accept=".xlsx,.xls"
      >
        <template #upload-button>
          <a-button type="primary">
            <template #icon><icon-upload /></template>
            选择文件
          </a-button>
        </template>
      </a-upload>
      <div class="upload-tip mt-base">
        <p>支持 .xlsx、.xls 格式的文件</p>
        <a-link @click="downloadTemplate">下载导入模板</a-link>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, markRaw, onUnmounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { 
  IconPlus, 
  IconEdit, 
  IconDelete,
  IconImport, 
  IconExport,
  IconUpload,
  IconSearch, 
  IconRefresh,
  IconPlayCircle,
  IconPauseCircle,
  IconTag,
  IconSync
} from '@arco-design/web-vue/es/icon';
import { useCargoStore, useCargoCategoryStore, useSupplierStore } from '@/stores';
import basicApi from '@/api/basic';

// 使用markRaw包装图标组件
const icons = {
  plus: markRaw(IconPlus),
  edit: markRaw(IconEdit),
  delete: markRaw(IconDelete),
  import: markRaw(IconImport),
  export: markRaw(IconExport),
  upload: markRaw(IconUpload),
  search: markRaw(IconSearch),
  refresh: markRaw(IconRefresh),
  playCircle: markRaw(IconPlayCircle),
  pauseCircle: markRaw(IconPauseCircle),
  tag: markRaw(IconTag),
  sync: markRaw(IconSync)
};

// 使用store
const cargoStore = useCargoStore();
const categoryStore = useCargoCategoryStore();
const supplierStore = useSupplierStore();

// 数据加载和分页
const loading = ref(false);
const tableData = ref([]);
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showPageSize: true
});

// 搜索表单
const searchForm = reactive({
  code: '',
  name: '',
  category: undefined,
  status: undefined
});

// 货物分类
const categoryOptions = ref([
  { label: '电子产品', value: 1 },
  { label: '办公用品', value: 2 },
  { label: '日用品', value: 3 }
]);

// 货物状态
const statusOptions = ref([
  { label: '正常', value: 1 },
  { label: '缺货', value: 2 },
  { label: '即将停产', value: 3 },
  { label: '新品', value: 4 },
  { label: '禁用', value: 5 }
]);

// 存储类型选项
const storageTypeOptions = ref([
  { label: '常温', value: 1 },
  { label: '冷藏', value: 2 },
  { label: '冷冻', value: 3 }
]);

// 状态颜色映射
const statusColorMap = {
  1: 'green',  // 正常
  2: 'orange', // 缺货
  3: 'red',    // 即将停产
  4: 'blue',   // 新品
  5: 'gray'    // 禁用
};

// 弹窗控制
const modalVisible = ref(false);
const importVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const formData = reactive({
  code: '',
  name: '',
  barcode: '',
  specification: '',
  unit: '',
  categoryId: undefined,
  weight: 0,
  price: 0,
  initialStock: 0,
  minStock: 0,
  maxStock: 0,
  productionDate: null,
  expirationDate: null,
  status: 1,
  description: ''
});

// 表单验证规则
const formRules = {
  code: [
    { required: true, message: '请输入货物编码' },
    { match: /^[A-Za-z0-9-]+$/, message: '货物编码只能包含字母、数字和连字符' }
  ],
  name: [
    { required: true, message: '请输入货物名称' },
    { maxLength: 50, message: '货物名称最多50个字符' }
  ],
  spec: [
    { required: true, message: '请输入规格' }
  ],
  unit: [
    { required: true, message: '请选择单位' }
  ],
  category_id: [
    { required: true, message: '请选择货物分类' }
  ],
  status: [
    { required: true, message: '请选择货物状态' }
  ],
  storage_type: [
    { required: true, message: '请选择存储类型' }
  ]
};

// 自动生成货物编码
const generateCargoCode = () => {
  // 使用固定前缀 'CARGO'
  const prefix = 'CARGO';
  // 添加时间戳后6位
  const timestampPart = Date.now().toString().slice(-6);
  // 添加3位随机数
  const randomSuffix = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  
  formData.code = `${prefix}-${timestampPart}-${randomSuffix}`.toUpperCase();
  console.log('自动生成的货物编码:', formData.code);
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '启用';
    case 2:
      return '禁用';
    case 3:
      return '下架';
    case 4:
      return '待审核';
    case 5:
      return '审核不通过';
    default:
      return '未知状态';
  }
};

// 获取存储类型文本
const getStorageTypeText = (type) => {
  const option = storageTypeOptions.value.find(item => item.value === type);
  return option ? option.label : '未知类型';
};

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 1:
      return 'green';
    case 2:
      return 'red';
    case 3:
      return 'orange';
    case 4:
      return 'blue';
    case 5:
      return 'gray';
    default:
      return '';
  }
};

// 获取操作按钮
const getActions = (record) => {
  return [
    {
      label: '编辑',
      icon: IconEdit,
      onClick: () => handleEdit(record)
    },
    {
      label: record.status === 5 ? '启用' : '禁用',
      icon: record.status === 5 ? IconPlayCircle : IconPauseCircle,
      onClick: () => handleToggleStatus(record)
    },
    {
      label: '删除',
      icon: IconDelete,
      status: 'danger',
      onClick: () => handleDelete(record)
    }
  ];
};

// 生命周期钩子
onMounted(() => {
  // 1. 先获取分类列表 
  fetchCategoryList();
  // 2. 获取单位列表
  fetchUnitList();
  // 3. 获取供应商列表
  fetchSupplierList();
  // 4. 获取货物列表
  fetchCargoList();
  
  // 添加监听器，每分钟刷新一次分类数据，确保分类选项保持最新
  const categoryRefreshInterval = setInterval(() => {
    fetchCategoryList();
  }, 60000); // 每分钟刷新一次
  
  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(categoryRefreshInterval);
  });
});

// 获取货物列表
const fetchCargoList = async () => {
  loading.value = true;
  try {
    const params = {
      keyword: searchForm.code || searchForm.name,
      category_id: searchForm.category,
      status: searchForm.status,
      page_num: pagination.current,
      page_size: pagination.pageSize
    };
    
    const result = await cargoStore.getCargoList(params);
    
    if (result.success) {
      tableData.value = result.data.list || [];
      pagination.total = result.data.pagination.total || 0;
      pagination.current = result.data.pagination.current || 1;
      pagination.pageSize = result.data.pagination.pageSize || 10;
      Message.success('获取货物信息成功');
    } else {
      Message.error(result.message || '获取货物列表失败');
    }
  } catch (error) {
    Message.error('获取货物列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const currentCategoryId = searchForm.category; // 保存当前选中的分类ID
    
    const result = await categoryStore.getCategoryList();
    
    if (result && result.success) {
      const categoryData = result.data || [];
      
      // 确保数据是数组格式
      if (Array.isArray(categoryData)) {
        categoryOptions.value = formatCategoryOptions(categoryData);
        
        // 如果之前有选中值，但新数据中没有这个值，重置分类
        if (currentCategoryId && !categoryOptions.value.some(option => option.value === currentCategoryId)) {
          searchForm.category = undefined;
        }
      } else {
        // 如果返回的不是数组，尝试从其他属性中获取
        if (categoryData.list && Array.isArray(categoryData.list)) {
          categoryOptions.value = formatCategoryOptions(categoryData.list);
        } else {
          Message.error('获取货物分类数据格式不正确');
        }
      }
    } else {
      Message.error('获取货物分类失败');
    }
  } catch (error) {
    Message.error('获取货物分类失败');
  }
};

// 获取单位列表
const unitOptions = ref([]);
const fetchUnitList = async () => {
  try {
    // 调用API获取单位列表
    const response = await basicApi.getUnitList();
    
    if (response && response.code === 0) {
      unitOptions.value = response.data || [];
      console.log('单位数据:', unitOptions.value);
    } else {
      // 如果API不可用，使用默认单位
      console.warn('获取单位列表失败，使用默认值');
      unitOptions.value = [
        { id: 1, name: '个' }, 
        { id: 2, name: '台' }, 
        { id: 3, name: '件' }, 
        { id: 4, name: '套' }, 
        { id: 5, name: '箱' }
      ];
    }
  } catch (error) {
    console.error('获取单位列表失败:', error);
    // 使用一些默认值作为备用
    unitOptions.value = [
      { id: 1, name: '个' }, 
      { id: 2, name: '台' }, 
      { id: 3, name: '件' }, 
      { id: 4, name: '套' }, 
      { id: 5, name: '箱' }
    ];
  }
};

// 获取供应商列表
const supplierOptions = ref([]);
const fetchSupplierList = async () => {
  try {
    const result = await supplierStore.getSupplierList({
      page_size: 100, // 获取足够的供应商数据用于下拉选择
      status: 1 // 只获取正常状态的供应商
    });
    
    if (result && result.success) {
      const supplierData = result.data.list || [];
      
      // 将供应商数据转换为下拉选项格式
      supplierOptions.value = supplierData.map(supplier => ({
        label: supplier.name,
        value: supplier.id
      }));
    } else {
      console.warn('获取供应商列表失败');
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error);
  }
};

// 格式化分类选项，将API返回的数据转换为选择器需要的格式
const formatCategoryOptions = (categories) => {
  if (!categories || !Array.isArray(categories)) {
    return [];
  }
  
  // 直接将所有分类添加到选项中，确保不丢失数据
  const options = categories.map(category => {
    const id = category.id || category.ID;
    const name = category.name || category.Name || '未命名分类';
    const level = category.level || category.Level || 1;
    const parentId = category.parent_id || category.parentId || category.ParentID || 0;
    
    // 根据层级添加缩进
    let label = name;
    if (level === 2) {
      label = `  └ ${name}`;
    } else if (level === 3) {
      label = `      └ ${name}`;
    }
    
    return {
      label,
      value: id,
      level,
      parentId
    };
  });
  
  return options;
};

// 分页变化
const onPageChange = (page) => {
  console.log('页码变化:', page, '总数据:', pagination.total, '当前数据长度:', tableData.value.length);
  pagination.current = page;
  fetchCargoList();
};

const onPageSizeChange = (pageSize) => {
  console.log('每页条数变化:', pageSize, '总数据:', pagination.total, '当前数据长度:', tableData.value.length);
  pagination.pageSize = pageSize;
  pagination.current = 1; // 切换每页条数时重置为第一页
  fetchCargoList();
};

// 打开新增弹窗
const openAddModal = () => {
  isEdit.value = false;
  resetFormData();
  modalVisible.value = true;
};

// 处理编辑
const handleEdit = (record) => {
  isEdit.value = true;
  Object.assign(formData, record);
  modalVisible.value = true;
};

// 处理提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    
    const data = { ...formData };
    // 处理表单数据
    
    let result;
    if (isEdit.value) {
      result = await cargoStore.updateCargo(data.id, data);
    } else {
      result = await cargoStore.createCargo(data);
    }
    
    if (result.success) {
      Message.success(isEdit.value ? '货物更新成功' : '货物添加成功');
      modalVisible.value = false;
      fetchCargoList();
    }
  } catch (error) {
    Message.error('操作失败: ' + (error.message || '未知错误'));
  } finally {
    submitLoading.value = false;
  }
};

// 关闭弹窗
const closeModal = () => {
  formRef.value?.resetFields();
  modalVisible.value = false;
};

// 处理导入
const handleImport = () => {
  importVisible.value = true;
};

// 处理导出
const handleExport = () => {
  // TODO: 调用导出接口
  Message.success('导出成功');
};

// 自定义上传请求
const customRequest = (options) => {
  const { file } = options;
  // TODO: 处理文件上传
};

// 下载模板
const downloadTemplate = () => {
  // TODO: 下载导入模板
};

// 处理导入提交
const handleImportSubmit = () => {
  // TODO: 处理文件导入
  importVisible.value = false;
  Message.success('导入成功');
};

// 处理删除
const handleDelete = async (record) => {
  try {
    const result = await cargoStore.deleteCargo(record.id);
    if (result.success) {
      Message.success('删除货物成功');
      fetchCargoList();
    } else {
      Message.error(result.message || '删除失败');
    }
  } catch (error) {
    Message.error('删除失败: ' + (error.message || '未知错误'));
  }
};

// 处理禁用/启用切换
const handleToggleStatus = async (record) => {
  try {
    // 当前状态: 1-启用, 2-禁用
    const currentStatus = record.status;
    // 切换目标状态
    const newStatus = currentStatus === 1 ? 2 : 1; // 1和2之间切换
    const statusText = newStatus === 1 ? '启用' : '禁用';
    
    const result = await cargoStore.updateCargoStatus(record.id, newStatus);
    if (result.success) {
      Message.success(`货物已${statusText}`);
      // 更新成功后刷新列表
      fetchCargoList();
    } else {
      Message.error(result.message || `${statusText}失败`);
    }
  } catch (error) {
    Message.error('操作失败: ' + (error.message || '未知错误'));
  }
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'status' || key === 'category' ? undefined : '';
  });
  fetchCargoList();
};

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    code: '',
    name: '',
    category_id: undefined,
    supplier_id: undefined,
    unit: '',
    spec: '',
    price: 0,
    description: '',
    minStock: 0,
    maxStock: 0,
    initialStock: 0,
    status: 1, // 默认为正常状态
    storage_type: 1,
    shelf_life: 0,
    manufacturer: '',
    remark: '',
    productionDate: null,
    expirationDate: null
  });
};

// 提交加载状态
const submitLoading = ref(false);

// 表格行选择
const selectedRowKeys = ref([]);

// 处理批量删除
const handleBatchDelete = async () => {
  if (selectedRowKeys.value.length === 0) {
    Message.warning('请至少选择一个货物');
    return;
  }
  
  Modal.confirm({
    title: '确认批量删除',
    content: `确定要删除已选择的${selectedRowKeys.value.length}个货物吗？此操作不可恢复。`,
    okText: '确定',
    cancelText: '取消',
    okButtonProps: {
      status: 'danger'
    },
    onBeforeOk: async (done) => {
      try {
        const result = await cargoStore.batchDeleteCargos(selectedRowKeys.value);
        if (result.success) {
          Message.success('批量删除货物成功');
          fetchCargoList();
          selectedRowKeys.value = [];
          done(); // 关闭对话框
        } else {
          Message.error(result.message || '批量删除失败');
          done(false); // 保持对话框打开
        }
      } catch (error) {
        Message.error('批量删除失败: ' + (error.message || '未知错误'));
        done(false); // 保持对话框打开
      }
    }
  });
};

// 获取单位名称
const getUnitName = (unitId) => {
  if (!unitId) return '-';
  const unit = unitOptions.value.find(item => item.id === unitId);
  return unit ? unit.name : unitId.toString();
};
</script>

<style lang="less" scoped>
@import '@/styles/variables.less';

.search-form {
  margin-bottom: 8px;
}

:deep(.arco-table) {
  .arco-table-th {
    background-color: #fafafa;
    font-weight: 500;
    color: var(--color-text-1);
  }
  
  .arco-table-td {
    color: var(--color-text-regular);
  }
  
  .arco-table-row:hover {
    background-color: #f5f7fa;
  }
}

:deep(.arco-form-item) {
  margin-bottom: 24px;
}

:deep(.arco-modal) {
  .arco-modal-header {
    border-bottom: 1px solid var(--color-border);
    padding: 16px 20px;
  }
  
  .arco-modal-body {
    padding: 20px;
  }
  
  .arco-modal-footer {
    border-top: 1px solid var(--color-border);
    padding: 12px 20px;
  }
}

:deep(.arco-form-item-label) {
  font-weight: 500;
}

.modal-footer {
  margin-top: 24px;
  text-align: right;
  border-top: 1px solid var(--color-neutral-3);
  padding-top: 16px;
}

:deep(.arco-radio-group-button) {
  flex-wrap: wrap;
  
  .arco-radio {
    margin-bottom: 8px;
  }
}

:deep(.arco-modal-footer .arco-btn),
:deep(.modal-footer .arco-btn) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
</style> 